package com.lingxu.api.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @program: ptmh
 * @ClassName JSONArrayToListConverter
 * @description:
 * @author: gxy
 * @create: 2025-07-18 12:42
 * @Version 1.0
 **/
public class JSONArrayToListConverter {

    public static <T> List<T> convert(JSONArray jsonArray, Class<T> targetType) throws Exception {
        List<T> resultList = new ArrayList<>();
        Map<String,String> fMap = new HashMap<>();
        //获取所有属性构成map,忽略大小写
        Field[] fields=targetType.getDeclaredFields();
        for (Field f:fields) {
            fMap.put(f.getName().toLowerCase(Locale.ROOT),f.getName());
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            T targetObject = targetType.newInstance();
            for (String key : jsonObject.keySet()) {
                Object value = jsonObject.get(key);
                //排除key中的 “_” 干扰
                String keyV = key.replaceAll("_","").toLowerCase(Locale.ROOT);
//                if(null!=value&&fMap.containsKey(keyV)&&String.valueOf(value).length()<3000) {
//                    ReflectUtil.setObjFieldVal(targetObject,fMap.get(keyV),value);
//                }
                if(null!=value&&fMap.containsKey(keyV)) {
                    ReflectUtil.setObjFieldVal(targetObject,fMap.get(keyV),value);
                }
            }
            resultList.add(targetObject);
        }
        return resultList;
    }

    public static void main(String[] args) throws Exception {
        JSONArray jsonArray = new JSONArray(Collections.singletonList("[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30}]"));
        List<Person> personList = JSONArrayToListConverter.convert(jsonArray, Person.class);

        for (Person person : personList) {
            System.out.println("Name: " + person.getName() + ", Age: " + person.getAge());
        }
    }
}
